package com.wh.simpleredis.manager;

import com.wh.simpleredis.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: HuiEr
 * @Date: 2020/3/6 21:07
 * @Description
 */
@Component
public class RedisManager {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonLock redissonLock;

    @Autowired
    private RedisTemplate redisTemplate;
    private Logger logger= LoggerFactory.getLogger(RedisManager.class);
    public void addValue(String key,String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }

    public String getValue(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    public String produceStock(){
        String lock="lock";
        String value= UUID.randomUUID().toString();
        try{
            Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lock, value, 30, TimeUnit.SECONDS);
            if (!flag){
                logger.info("redis中已经有lock键了，返回");
                return "目前排队人数过多，稍后再试。。。。";
            }
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("tickets"));
            if(stock>0){
                stringRedisTemplate.opsForValue().set("tickets",String.valueOf(stock-1));
            }
            else {
                logger.info("票已经售完了。。。");
                return "票已经售完了。。。";
            }
        }finally {
            if(value.equals(stringRedisTemplate.opsForValue().get(lock))){
                stringRedisTemplate.delete(lock);
            }
        }
        return "扣减了一个库存票";
    }

    public String produceStockRedisson(){
        String lock="lock";
        try{
            boolean lock1 = redissonLock.lock(lock);
            if (!lock1) {
                return "目前排队人数过多，稍后再试";
            }
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("tickets"));
            if(stock>0){
                stringRedisTemplate.opsForValue().set("tickets",String.valueOf(stock-1));
            }
            else {
                return "库存不足。。。。";
            }
        }finally {
           redissonLock.unlock(lock);
        }
        return "库存减一。。。。";
    }

    /*public String saveduixiang(){
        String string = new User("wang", "hui").toString();
        stringRedisTemplate.opsForValue().set("user",string);
        return string;
    }*/

    public String saveduixiang(){
        redisTemplate.opsForValue().set("user",new User("wang", "hui"));
        return new User("wang", "hui").toString();
    }

    public String getduixiang(){
        return stringRedisTemplate.opsForValue().get("user");
    }
}
